package com.attendance.sz.net;

import android.util.Log;

import com.attendance.sz.utils.Entity;
import com.attendance.sz.utils.Session;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016-03-22.
 */
public class SmartAPI {
    public static final String BASE_URL = Session.getDownPhotoUrl();//"http://10.10.8.181:8080/WebService.asmx";
    //public static final String BASE_URL = "http://11.35.200.3:8082/SmartAPI.asmx/";
    private static final int DEFAULT_TIMEOUT = 5;
    private Retrofit retrofit;
    private SmartService smartService;

    //构造方法私有
    private SmartAPI() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//                .baseUrl(Session.getDownPhotoUrl()+"/")
                .baseUrl(BASE_URL+"/")
                .build();

        smartService = retrofit.create(SmartService.class);

    }



    //在访问HttpMethods时创建单例
    private static class SingletonHolder{
        private static final SmartAPI INSTANCE = new SmartAPI();
    }

    //获取单例
    public static SmartAPI getInstance(){
        return SingletonHolder.INSTANCE;
    }

    /**
     * 上传相片
     * @param subscriber 由调用者传过来的观察者对象
     */
    public void queryAccountInfo(Subscriber<Entity> subscriber, String FileName ,String Buffer ){
        Observable observable = smartService.queryAccountInfo(FileName,Buffer);
        toSubscribe(observable,subscriber);
    }
    public void GetEmployeeImage(Subscriber<Entity> subscriber, String CardID ){
        Observable observable = smartService.GetEmployeeImage(CardID);
        toSubscribe(observable,subscriber);
    }

    private <T> void toSubscribe(Observable<T> o, Subscriber<T> s){
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }
 }